/**
 * @desc    公共处理类
 *
 * @author    Damen
 * @date    2017-08-08
 *
 * @constructor
 */
function CommonClass() {
    this.config = {
        BASE_ACTION: webRoot + "/base/baseAction",
        GBPS_MILLS: 1024 * 1024,
        MBPS_MILLS: 1024,
        PRIVILEGE_URL: ['/pages/home/home.jsp']
    };

    /**
     * 判断是否为空
     * @param object
     */
    this.isEmpty = function (object) {
        if (typeof(object) != "undefined" && object != null && object !== '') {
            return false;
        } else {
            return true;
        }
    };
    this.isValue = function (object, defalutVal) {
        if (!this.isEmpty(object)) {
            return object;
        } else {
            if (!this.isEmpty(defalutVal)) {
                return defalutVal;
            } else {
                return '';
            }
        }
    };
    /**
     * 公共请求方法
     * @param data
     *      sqlKey  : 请求SQL
     *      paramMap    : 参数
     * @param callback
     * @constructor
     */
    this.BaseAction = function (data, callback) {
        $.ajax({
            type: 'post',
            url: this.config.BASE_ACTION,
            cache: false,
            data: {
                sqlKey: data.sqlKey,
                paramMap: JSON.stringify(data.paramMap)
            },
            dataType: 'json',
            success: function (data) {
                if ($.isFunction(callback)) {
                    callback(data);
                }
            },
            error: function () {
            }
        });
    };

    /**
     * 公共请求方法
     * @param url : Controller请求地址
     * @param data
     * @param callback
     * @constructor
     */
    this.AjaxAction = function (url, data, callback) {
        $.ajax({
            type: 'post',
            url: url,
            cache: false,
            data: data || {},
            dataType: 'json',
            success: function (data) {
                if ($.isFunction(callback)) {
                    callback(data);
                }
            },
            error: function () {
            }
        });
    };

    /**
     * 数据字典下拉框
     * @param control    : 下拉框控件
     * @param dataType    : 数据字典类型
     * @param callback    : 回调函数
     */
    this.loadOriDataCombo = function (control, dataType, isAllName, callback) {
        var me = this;
        $.ajax({
            type: 'post',
            url: webRoot + "/base/baseAction.do",
            cache: false,
            data: {
                sqlKey: "com.livect.portal.dao.sys.SysOriDataCodeDao.findDataCodeListByType",
                paramMap: JSON.stringify({oriCategoryId: dataType})
            },
            dataType: 'json',
            success: function (data) {
                me.setComboData(control, data, "oriCodeId", "oriCodeName", isAllName, callback);
            },
            error: function () {
                return;
            }
        });
    };

    /**
     *  公共的下拉框数据加载
     * @param control
     * @param params
     *      sqlKey  : 请求SQL
     *      paramMap    : 参数
     * @param id
     * @param text
     * @param isAllName
     * @param callback
     */
    this.loadCommonCombo = function (control, params, id, text, isAllName, callback) {
        var me = this;
        $.ajax({
            type: 'post',
            url: webRoot + "/base/baseAction.do",
            cache: false,
            data: {
                sqlKey: params.sqlKey,
                paramMap: JSON.stringify(params.paramMap)
            },
            dataType: 'json',
            success: function (data) {
                me.setComboData(control, data, id, text, isAllName, callback);
            },
            error: function () {
                return;
            }
        });
    };

    /**
     *  设置下拉框值
     * @param callback
     */
    this.setComboData = function (control, data, id, text, isAllName, callback) {
        control.empty();//清空下拉框
        if (isAllName) {
            control.append("<option value=''>&nbsp;" + isAllName + "</option>");
        }
        $.each(data, function (i, item) {
            control.append("<option value='" + eval("item." + id) + "'>&nbsp;" + eval("item." + text) + "</option>");
        });
        if ($.isFunction(callback)) {
            callback(data);
        }
    };

    /**
     * 表单赋值
     * @param formId    表单id
     * @param formData
     */
    this.setForm = function (formId, formData) {
        var me = this;
        var formEl = [" input", " select", " textarea"];
        $.each(formEl, function (eIndex, el) {
            $.each($("#" + formId + el), function (index, input) {
                input.value = me.isValue(eval("formData." + this.name), '');
                $(this).change();
            });
        });
    };
    this.fieldVaild = function () {
        var rules = $(".form-info input[data-rules*='{']");
        $.each(rules, function (index, rule) {
            $(this).change();
        });
    };
    /**
     * 获取表单值
     * @param formId    表单id
     * @returns {{}}
     */
    this.getForm = function (formId) {
        var formData = {};
        var formArr = $('#' + formId).serializeArray();
        $.each(formArr, function () {
            formData[this.name] = this.value;
        });
        return formData;
    };

    this.setRecord = function (form, record) {
        var _self = form,
            fields = _self.getFields();
        BUI.each(fields, function (field) {
            var name = field.get('name');
            _self._setFieldValue(field, record[name]);
        });
    }
    /**
     * 获取当前格式化时间
     * @param formatStr
     *      格式 YYYY/yyyy/YY/yy 表示年份
     *      MM/M 月份
     *      W/w 星期
     *      dd/DD/d/D 日期
     *      hh/HH/h/H 时间
     *      mm/m 分钟
     *      ss/SS/s/S 秒
     * @param addDayCount   时间前后移动天数
     * @returns {*|string}
     */
    this.getCurDateTime = function (formatStr, addDayCount) {
        var myDate = new Date(new Date().getTime() + 86400000 * this.isValue(addDayCount, 0));
        return this.getDate2String(myDate, formatStr);        //获取日期与时间
    };
    /**
     *
     * @param formatStr 时间格式化
     * @param addTimeCount  时间戳前后移动
     */
    this.getCurDateDiff = function (formatStr, addTimeCount) {
        var myDate = new Date(new Date().getTime() + this.isValue(addTimeCount, 0));
        return this.getDate2String(myDate, formatStr);        //获取日期与时间
    };


    /**
     *
     * @param date  时间
     * @param format 格式化
     */
    this.getDate2String = function (myDate, format) {
        var formatStr = format || 'yyyy-MM-DD HH:mm:ss';
        var Week = ['日', '一', '二', '三', '四', '五', '六'];

        formatStr = formatStr.replace(/yyyy|YYYY/, myDate.getFullYear());
        formatStr = formatStr.replace(/yy|YY/, (myDate.getYear() % 100) > 9 ? (myDate.getYear() % 100).toString() : '0' + (myDate.getYear() % 100));

        var month = myDate.getMonth() + 1;
        formatStr = formatStr.replace(/MM/, month > 9 ? month.toString() : '0' + month);
        formatStr = formatStr.replace(/M/g, month);

        formatStr = formatStr.replace(/w|W/g, Week[myDate.getDay()]);

        formatStr = formatStr.replace(/dd|DD/, myDate.getDate() > 9 ? myDate.getDate().toString() : '0' + myDate.getDate());
        formatStr = formatStr.replace(/d|D/g, myDate.getDate());

        formatStr = formatStr.replace(/hh|HH/, myDate.getHours() > 9 ? myDate.getHours().toString() : '0' + myDate.getHours());
        formatStr = formatStr.replace(/h|H/g, myDate.getHours());
        formatStr = formatStr.replace(/mm/, myDate.getMinutes() > 9 ? myDate.getMinutes().toString() : '0' + myDate.getMinutes());
        formatStr = formatStr.replace(/m/g, myDate.getMinutes());

        formatStr = formatStr.replace(/ss|SS/, myDate.getSeconds() > 9 ? myDate.getSeconds().toString() : '0' + myDate.getSeconds());
        formatStr = formatStr.replace(/s|S/g, myDate.getSeconds());

        return formatStr;
    };

    this.getDateDiffArray = function (startTime, endTime) {
        var dateDiffArr = new Array();
        dateDiffArr.push(startTime);
        if (startTime < endTime) {
            endTime = endTime || this.getCurDateTime("yyyy-MM-DD", 0);
            var isEnd = 0;
            var myDate = new Date(startTime.replace(/-/g, "/"));
            while (isEnd == 0) {
                myDate = new Date(myDate.getTime() + 86400000);
                var myTime = this.getDate2String(myDate, "yyyy-MM-DD");
                dateDiffArr.push(myTime);
                if (myTime >= endTime) {
                    isEnd = 1;
                }
            }
        }
        return dateDiffArr;
    };
    /**
     * 获取月份列表
     * monthNum    月份的数量
     */
    this.getDateMonth = function (monthArr, monthNum) {
        if (!monthArr || monthArr.length == 0) {
            monthArr = new Array();
        }
        monthArr.push(this.getCurDateTime("YYYY-MM"));
        var myDate = new Date();
        var curYear = myDate.getFullYear();
        var curMonth = myDate.getMonth() + 1;
        curMonth = curMonth > 9 ? curMonth.toString() : '0' + curMonth;
        for (var num = 0; num < monthNum - 1; num++) {
            curMonth = Number(curMonth) - 1;
            if (curMonth == 0) {
                curYear = Number(curYear) - 1;
                curMonth = "12";
            } else {
                curMonth = curMonth > 9 ? curMonth.toString() : '0' + curMonth;
            }
            monthArr.push(curYear + "-" + curMonth);
        }
        return monthArr;
    };

    /**
     * 获取最大带宽单位
     * @param traffic   byte
     * @param type
     */
    this.getTrafficUnit = function (traffic) {
        var trafficUnit = "Kbps";
        var formula = '/1024';
        if (traffic / 1024 / this.config.GBPS_MILLS > 10) {
            trafficUnit = "Gbps";
            formula = '/1024/1024/1024';
        } else if (traffic / 1024 / this.config.MBPS_MILLS > 10) {
            trafficUnit = "Mbps";
            formula = '/1024/1024';
        }
        var trafficParam = {
            trafficUnit: trafficUnit,
            formula: formula
        };
        return trafficParam;
    };

    /**
     * 获取链接参数
     * @returns {*}
     */
    this.getUrlParams = function () {
        var url = location.search;
        if (url) {
            url = url.replace("?", '"');
            var flag = true;
            while (flag) {
                var length = url.length;
                url = url.replace("&", '","');
                url = url.replace("=", '":"');
                if (url.length == length) {
                    flag = false;
                }
            }
            url = "{" + url + '"}';
            return $.parseJSON(url);
        } else {
            return null;
        }
    };
    /**
     * 判断链接是否有效
     * @returns {boolean}
     */
    this.privilegeUrl = function () {
        var me = this;
        var pathName = window.location.pathname;
        var isPrivilege = false;
        if (pathName == "/" || pathName.length < 5) {
            return true;
        }
        $.each(me.config.PRIVILEGE_URL, function (index, url) {
            if (pathName.indexOf(url) >= 0) {
                isPrivilege = true;
            }
        });
        if (!isPrivilege) {
            var urlParams = me.getUrlParams();
            if (urlParams && urlParams.menuKey && urlParams.menuKey.length == 36) {
                isPrivilege = true;
            }
        }
        return isPrivilege;
    };
    /**
     * 生产GUID
     * @returns {string}
     */
    this.guid = function () {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    };

    /**
     * 页面按键监听
     */
    this.onKeyDown = function (keyCode, callback) {
        document.onkeydown = function (event) {
            var e = event || window.event || arguments.callee.caller.arguments[0];
            if (e && e.keyCode == keyCode) {
                if ($.isFunction(callback)) {
                    callback();
                }
            }
        };
    };
    /**
     * 删除表格数据
     * @param grid
     * @param store
     * @param url
     */
    this.deleteGridData = function (grid, store, url,idKey) {
        var selections = grid.getSelection();
        if (selections.length == 0) {
            BUI.Message.Alert('请选择一条记录！', function () {
            }, 'info');
            return;
        }
        var id = [];
        if(idKey==null||idKey==undefined){
            idKey="id"
        }
        for (var i = 0; i < selections.length; i++) {
            id.push(selections[i][idKey]);
        }
        BUI.Message.Confirm('确认删除记录？', function () {
            $.ajax({
                type: 'POST',
                url: url,
                data: {ids: id.join(",")},
                success: function (data) {
                    if (data.success) {
                        store.load()
                    } else {
                        BUI.Message.Alert(data.errorMessage, 'error');
                    }

                }
            });
        }, 'question');

    };
}